import {
    _decorator, Color, Component, director, EventTouch, Input, Node,
    Sprite, tween, UITransform, Vec2, Vec3
} from 'cc';
import { HoleAction } from './HoleAction';
import { PinAction } from './PinAction';
import { ColorDate } from './ColorDate';
import { AudioManger } from './AudioManger';
import { Clips, events } from './Enums';
import { Tools } from './Tools';
import { Global } from './Global';
import { CatColorRules } from './CatColorRules';

const { ccclass, property } = _decorator;

@ccclass('CatAction')
export class CatAction extends Component {
    @property({ type: Node }) lock: Node;
    @property({ type: Sprite }) box_1_img: Sprite;
    @property({ type: Sprite }) box_2_img: Sprite;

    private cat_color: ColorDate;
    private default_position: Readonly<Vec3>;
    private defalut_lock: boolean = false;
    public  isLocked: boolean = false;

    onLoad(): void {
        this.default_position = this.node.getPosition().clone();
        this.defalut_lock = this.lock.active;
    }

    start() {
        this.node.on(Input.EventType.TOUCH_START, this.touch_start, this);
    }

    /** 初始化当前猫位置 */
    public init_cat() {
        this.set_lock_unlock(this.defalut_lock);
        this.clear_pins();
        this.node.setPosition(this.default_position);

        if (this.isLocked) return;

        this.cat_color = CatColorRules.get_next_cat_color(CatColorRules.r_0());
        if (!this.cat_color) return;

        this.set_img(this.cat_color, 255);
    }

    public get_cat_color(): ColorDate {
        return this.cat_color;
    }

    public set_lock_unlock(lock: boolean) {
        this.isLocked = lock;
        this.node.children.forEach(child => {
            const hole = child.getComponent(HoleAction);
            if (hole) child.active = !lock;
        });

        this.lock.active = lock;
        this.box_2_img.node.active = !lock;

        if (lock) {
            this.set_img(ColorDate.new_bean(0, 0, 0, 0), 100);
        }
    }

    private touch_start(e: EventTouch) {
        if (this.isLocked) {
            AudioManger.instance.playSound(Clips.btn_1);
            Global.props_action.show_box(this);
        }
    }

    private get_hole_arr(): Node[] {
        return this.node.children.filter(n => n.getComponent(HoleAction));
    }

    public get_pin_num(): number {
        return this.node.children.filter(n => n.getComponent(PinAction)).length;
    }

    public get_temp_hole_num(): number {
        return this.get_hole_arr().length - this.get_pin_num();
    }

    private get_temp_position(): Vec3 | null {
        const holes = this.get_hole_arr();
        const index = this.get_pin_num();
        return holes[index]?.position ?? null;
    }

    public check_able_put(pin: PinAction): boolean {
        return (
            !this.isLocked &&
            this.cat_color?.id === pin.pin_color.id &&
            this.get_temp_hole_num() > 0
        );
    }

    public put_pin(pin: PinAction, delay = 0): boolean {
        const target_hole_pos = this.get_temp_position();
        if (!target_hole_pos) return false;

        const world_pos = pin.node.getWorldPosition();
        const local_pos = this.node.getComponent(UITransform).convertToNodeSpaceAR(world_pos);
        this.node.addChild(pin.node);
        pin.node.setPosition(local_pos);
        pin.remove_collider();

        const run_completed = this.get_temp_hole_num() <= 0;
        this.play_insert_tween(pin, run_completed, target_hole_pos, delay);
        return true;
    }

    private play_insert_tween(pin: PinAction, run_completed: boolean, target: Vec3, delay: number) {
        const approach = pin.node.position.clone().lerp(target, 0.1);

        tween(pin.node)
            .delay(delay)
            .to(0.2, { scale: new Vec3(2, 2), position: approach, angle: 360 }, { easing: 'quadInOut' })
            .to(0.3, { position: target }, { easing: 'quadInOut' })
            .call(() => {
                pin.pos_hole?.hide();
                if (run_completed) this.full_complete();
            })
            .to(0.2, { scale: new Vec3(1, 1) }, { easing: 'quadInOut' })
            .start();
    }

    /** 钉子插满后执行奖励动画及重置逻辑 */
    private full_complete() {
        Global.coins_action.put_coins(this.get_pin_num(), this.node.getWorldPosition());

        this.shake_self(() => {
            const fly_to = this.default_position.clone().add(new Vec3(0, 300));
            tween(this.node)
                .to(0.15, { position: fly_to }, Global.our_easing)
                .call(() => {
                    AudioManger.instance.playSound(Clips.pin_3);
                    this.cat_color = null;
                    Global.pin_prgress_computed(this.get_pin_num());
                    this.clear_pins();
                    director.emit(events.check_completed, this);
                })
                .start();
        });
    }

    /** 抖动动画 */
    private shake_self(callback?: Function) {
        const base = this.node.getPosition().clone();
        const shakeSeq = tween(this.node);
        for (let i = 0; i < 4; i++) {
            shakeSeq
                .to(0.05, { position: new Vec3(base.x + 6, base.y) }, Global.our_easing)
                .to(0.05, { position: new Vec3(base.x - 6, base.y) }, Global.our_easing);
        }
        shakeSeq
            .to(0.05, { position: base }, Global.our_easing)
            .call(() => callback?.())
            .start();
    }

    public clear_pins() {
        Tools.clearFromParent(this.node, PinAction);
    }

    private set_img(color: ColorDate, alpha: number) {
        if (this.box_1_img) {
            this.box_1_img.color = new Color(color.r, color.g, color.b, alpha);
        }
    }

    public async into_scence(offset: Vec2 = new Vec2(-600, 0)) {
        if (this.isLocked) {
            this.node.setPosition(this.default_position);
            return;
        }

        const levelMap = {
            1: CatColorRules.r_0,
            2: CatColorRules.r_0,
            3: CatColorRules.r_1,
            4: CatColorRules.r_2,
            5: CatColorRules.r_3,
            6: CatColorRules.r_3,
        };
        const rule = levelMap[Global.cur_lvl] || CatColorRules.r_4;
        this.cat_color = CatColorRules.get_next_cat_color(rule());

        console.log("into_scence ---->>>>>>>>> remain cat>>", CatColorRules.cat_color_arr.length);
        if (!this.cat_color) {
            console.log("没有颜色了");
            return;
        }

        this.set_img(this.cat_color, 255);

        const fromPos = this.default_position.clone().add(new Vec3(offset.x, offset.y));
        this.node.setPosition(fromPos);
        tween(this.node)
            .to(0.2, { position: this.default_position.clone() }, Global.our_easing)
            .call(() => this.load_pin())
            .start();
    }

    /** 自动装载匹配颜色的钉子 */
    public load_pin() {
        const pin_arr: PinAction[] = [];
        Global.bucket_action.get_pin_arr_by_color_id(this.cat_color.id, pin_arr);
        Global.layer_empty_action.get_pin_by_color(this.cat_color.id, pin_arr);
        pin_arr.forEach(pin => {
            if (this.check_able_put(pin)) {
                this.put_pin(pin, 0.2);
            }
        });
    }
}
